<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <h1>双向数据绑定模拟</h1>
    <h3 id="cc"></h3>
    <input id="txt" type="text">
    <button id="add">添加</button>
    <hr>
    <div id="m_arr">


    </div>
    <script>
        let m_arr = getId('m_arr')
        let h3 = getId('cc')
        let inp = getId('txt')
        let add = getId('add')

        let cc = { _value: '', _arr: [],arr:[] }

        let newArr = []
        function getId(id) {
            return document.getElementById(id)
        }

        inp.onkeydown = function (e) {
            // console.log(e)
            cc.value = e.target.value
        }
        inp.onkeyup = function (e) {
            // console.log(e)
            cc.value = e.target.value
        }
        // 当我点击添加得时候  拿到 最新改变得input值 追加到cc对象得arr里  然后改变从而做些什么  
        let inp_value;

        add.onclick = function () {
            // cc.arr = []
            console.log(inp.value)
            cc.arr = [...cc.arr, inp.value]
            console.log(cc.arr)
        }
        Object.defineProperty(cc, 'value', {

            set(newValue) {
                console.log(newValue)
                h3.innerHTML = newValue
                inp_value = newValue
                this._value = newValue
                console.log(inp_value)
            },
            get() {
                return this._value
            }
        })
        console.log(cc)
        Object.defineProperty(cc, 'arr', {
            set(newValue) {
        
                this._arr = newValue
                newArr = this._arr
                // 当这个数组改变得时候 相应得改变执行方法
                console.log(newArr)
                m_arr.innerHTML = ''    // 先清除页面上的元素 再重新遍历数组生成元素
                change(newArr)

            },
            get() {
                return this._arr
            },
        })

        function change(dd) {
            console.log(cc)
            dd.forEach((item, index) => {
                let h3 = document.createElement('h3')
                let  span = document.createElement('span')
                span.id=index
                span.innerHTML="删除"
                h3.innerHTML = item
                m_arr.appendChild(h3)
                m_arr.appendChild(span)
                span.onclick = function (e) {
                    console.log(this.id)
                    dd.splice(this.id,1)
                    cc.arr=dd
                }
            })
           
        }

    </script>
</body>

</html>